package autobazarreader;

import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
 * This class parsing http://avtobazar.ua/poisk/avto pages that containts cars to sale
 * @author Ahmad Samir
 */
public class CarsSales {
    
    private static final Logger LOGGER = Logger.getLogger(CarsSales.class);
    public CarsSales() throws IOException {
        DOMConfigurator.configure("log4j.xml");
    }
    
    static private void parser(Connection con) throws IOException {
        Document doc = con.get();
        Elements nameList = doc.select(".fn");
        Elements infoList = doc.select(".main_info");
        String[] infoString;
        
        for (int i = 0; i < nameList.size(); i++) {
            Elements carPrice = doc.select(".price_grn[title*=" + nameList.get(i).text() + "]");
            LOGGER.info("Car: " + nameList.get(i).text() + ";");
            if (carPrice.isEmpty()) {
                LOGGER.info("Price: no Price;");
            } else {
                LOGGER.info("Price: " + carPrice.get(0).text() + ";");
            }
            infoString = infoList.get(i).html().replaceAll("<li>|(?<!цвет)\\s+", "").split("</li>");
            int j = 0;
            LOGGER.info("Engine: " + infoString[j].replace("&nbsp", ""));
            LOGGER.info("Mileage: " + infoString[j + 1].replace("&nbsp", ""));
            LOGGER.info("Trans: " + infoString[j + 2].replace("&nbsp", ""));
            LOGGER.info("Color: " + infoString[j + 3].replace("&nbsp", "") + "\n");
        }
    }

    /**
     * @param millsTimeOut - time to wait answer from server
     * @param pages - how many pages you want to parse from 1 to this value
     */
    public void parseAll(int pages, int millsTimeOut) throws IOException {
        for (int i = 1; i <= pages; i++) {
            Connection con = Jsoup.connect("http://avtobazar.ua/poisk/avto/?page=" + i);
            con.timeout(millsTimeOut);
            parser(con);
        }
    }
}
